package com.lancoo.answer.widget.combinationView;

import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ivan.GlideEngine;
import com.ivan.easyphotos.EasyPhotos;
import com.lancoo.answer.R;
import com.lancoo.answer.model.bean.ItemAsk;
import com.lancoo.answer.model.bean.Type;
import com.lancoo.answer.util.DpUtils;
import com.lancoo.answer.view.fragment.composition.adapter.ImageAdapter;
import com.lancoo.answer.widget.audioPlayView.AudioPlayCallBack;
import com.rxjava.rxlife.RxLife;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2021/12/15 13:42
 * Description:作文题查看评阅状态view
 */
public class CompositionAnswerResultSubView extends RecyclerView.Adapter<CompositionAnswerResultSubView.VH> {


    private final List<ItemAsk> itemAskList;

    public CompositionAnswerResultSubView(List<ItemAsk> itemAskList) {
        this.itemAskList = itemAskList;
    }

    @NonNull
    @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.ev_list_composition_answer_looking_layout, parent, false);
        return new VH(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        holder.initData(itemAskList.get(position));
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position, @NonNull List<Object> payloads) {
        super.onBindViewHolder(holder, position, payloads);
       if(payloads.contains("pause")){
           holder.pause();
        } else if(payloads.contains("release")){
           holder.release();
        }
    }

    @Override
    public int getItemCount() {
        return itemAskList.size();
    }

    public static class VH extends RecyclerView.ViewHolder  {

        private ChildAudioView childAudioView;

        public VH(@NonNull View itemView) {
            super(itemView);
        }


        private void initData(ItemAsk itemAsk){
            TextView tv_order = itemView.findViewById(R.id.tv_order);
            tv_order.setText(itemAsk.getAskTip());
            String imagePath = itemAsk.getImagePath();
            String audioPath = itemAsk.getAudioPath();
            String stuAnswer = itemAsk.getStuAnswer();
            List<String> imagePathList = new ArrayList<>();
            if(!TextUtils.isEmpty(imagePath)){
                imagePathList.add(imagePath);
            }

            if(TextUtils.isEmpty(stuAnswer)&&
                    TextUtils.isEmpty(audioPath)&&
                    (imagePathList.size()==0||TextUtils.isEmpty(imagePathList.get(0)))){
                TextView tv_myAnswer= itemView.findViewById(R.id.tv_my_answer);
                tv_myAnswer.setText("未填写");
                tv_myAnswer.setVisibility(View.VISIBLE);
            }else{
                if(imagePathList.size()>0&&
                        !TextUtils.isEmpty(imagePathList.get(0))){
                    loadPictureAnswer(imagePathList);
                }
                if(!TextUtils.isEmpty(stuAnswer)){
                    loadTxtAnswer(stuAnswer);
                }
                if(!TextUtils.isEmpty(audioPath)){
                    loadAudioAnswer(audioPath);
                }
            }
        }

        /**
         * 加载图片作答内容
         * @param imagePathList 图片作答内容
         */
        private void loadPictureAnswer(final List<String> imagePathList){
            ViewStub viewStub = itemView.findViewById(R.id.viewstub_composition_answer_looking_picture);
            if(viewStub!=null){
                viewStub.inflate();
            }
            RecyclerView mRecyclerView = itemView.findViewById(R.id.recyclerView);
            mRecyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(),LinearLayoutManager.HORIZONTAL,false));
            ImageAdapter mAdapter = new ImageAdapter(imagePathList,1);
            mAdapter.setImageOperateCallBack(new ImageAdapter.ImageOperateCallBack() {

                @Override
                public void gotoImageLibChoice() {
                }

                @Override
                public void deletChoiceImage(int position){
                }

                @Override
                public void lookChoiceImage(int position){
                    EasyPhotos.startPreviewPaths((FragmentActivity)
                            itemView.getContext(), GlideEngine.getInstance(), imagePathList,true,position);
                }

            });
            mRecyclerView.setAdapter(mAdapter);
            int dp8= DpUtils.dip2px(itemView.getContext(),8);
            ViewGroup.LayoutParams layoutParams =  mRecyclerView.getLayoutParams();
            if(layoutParams instanceof RelativeLayout.LayoutParams){
                RelativeLayout.LayoutParams relate= (RelativeLayout.LayoutParams) layoutParams;
                relate.setMarginStart(-dp8);
                relate.setMarginEnd(0);
                relate.topMargin=dp8;
                mRecyclerView.setLayoutParams(relate);
            }else if(layoutParams instanceof LinearLayout.LayoutParams){
                LinearLayout.LayoutParams layout= (LinearLayout.LayoutParams) layoutParams;
                layout.setMarginStart(-dp8);
                layout.setMarginEnd(0);
                layout.topMargin=dp8;
                mRecyclerView.setLayoutParams(layout);
            }

        }


        /**
         * 加载文本作答内容
         * @param stuAnswer 文本作答内容
         */
        private void loadTxtAnswer(String stuAnswer){
            Log.e("eee","加载文本作答内容"+stuAnswer);
            if(TextUtils.isEmpty(stuAnswer)){
                return;
            }
            ViewStub viewStub = itemView.findViewById(R.id.viewstub_composition_answer_looking_txt);
            if(viewStub!=null){
                viewStub.inflate();
            }
            EditText editText = itemView.findViewById(R.id.edittext);
            editText.setVisibility(View.VISIBLE);

            editText.setBackgroundResource(R.drawable.ev_shape_3_corners_half_f7_bg);
            editText.setEnabled(false);
            editText.setText(stuAnswer);
            editText.setMinHeight(0);
            editText.setMinLines(1);
            TextView tv_answerCount=itemView.findViewById(R.id.tv_answer_count);
            tv_answerCount.setVisibility(View.VISIBLE);
            editText.setVisibility(View.VISIBLE);
            Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                        int count=0;
                        if(!TextUtils.isEmpty(stuAnswer)){
                            String[] split = stuAnswer.replace("\n"," ").split(" ");
                            count=split.length;
                            for (String str : split) {
                                if (str.isEmpty()) {
                                    count--;
                                }
                            }
                        }
                        emitter.onNext(Math.max(count,0));
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .as(RxLife.as(itemView,true))
                    .subscribe(integer -> {
                        SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                        spannableStringBuilder.append("Word Count:");
                        SpannableString spannableString=new SpannableString(""+integer);
                        spannableString.setSpan(new ForegroundColorSpan(0xff666666),0,spannableString.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        spannableStringBuilder.append(spannableString);
                        tv_answerCount.setText(spannableStringBuilder);
                    },error->{});
            int dp12= DpUtils.dip2px(itemView.getContext(),12);
            ViewGroup.LayoutParams layoutParams = tv_answerCount.getLayoutParams();
            if(layoutParams instanceof LinearLayout.LayoutParams){
                LinearLayout.LayoutParams layout= (LinearLayout.LayoutParams) layoutParams;
                layout.setMarginStart(0);
                layout.setMarginEnd(0);
                layout.topMargin=dp12;
                tv_answerCount.setLayoutParams(layout);
            }else  if(layoutParams instanceof RelativeLayout.LayoutParams){
                RelativeLayout.LayoutParams layout= (RelativeLayout.LayoutParams) layoutParams;
                layout.setMarginStart(0);
                layout.setMarginEnd(0);
                layout.topMargin=dp12;
                tv_answerCount.setLayoutParams(layout);
            }
            ViewGroup.LayoutParams layoutParams1 = editText.getLayoutParams();
            if(layoutParams1 instanceof LinearLayout.LayoutParams){
                LinearLayout.LayoutParams layout= (LinearLayout.LayoutParams) layoutParams1;
                layout.width= RelativeLayout.LayoutParams.MATCH_PARENT;
                layout.height= RelativeLayout.LayoutParams.WRAP_CONTENT;
                layout.bottomMargin=0;
                layout.leftMargin=0;
                layout.rightMargin=0;
                editText.setLayoutParams(layout);
            }else  if(layoutParams1 instanceof RelativeLayout.LayoutParams){
                RelativeLayout.LayoutParams layout= (RelativeLayout.LayoutParams) layoutParams1;
                layout.width= RelativeLayout.LayoutParams.MATCH_PARENT;
                layout.height= RelativeLayout.LayoutParams.WRAP_CONTENT;
                layout.bottomMargin=0;
                editText.setLayoutParams(layout);
            }
        }


        /**
         * 加载图片作答内容
         * @param audioPath 音频作答内容
         */
        private void loadAudioAnswer(final String audioPath){
            ViewStub viewStub = itemView.findViewById(R.id.viewstub_composition_answer_looking_audio);
            if(viewStub!=null){
                viewStub.inflate();
            }
            childAudioView = itemView.findViewById(R.id.child_audio_view);
            childAudioView.setAudioPath(audioPath);
            childAudioView.setAudioTxt(R.string.ev_my_audio);
            childAudioView.setCallBack(new AudioPlayCallBack() {
                @Override
                public void onAudioPlay() {
                    super.onAudioPlay();
                    pauseOtherAudio();
                }
            });

        }

        private void pauseOtherAudio(){
            if(getBindingAdapter()==null){
                return;
            }
            int itemCount = getBindingAdapter().getItemCount();
            int currentIndex=getBindingAdapterPosition();
            for (int i = 0; i < itemCount; i++) {
                if(i!=currentIndex){
                    getBindingAdapter().notifyItemChanged(i,"pause");
                }
            }
        }

        private void pause(){
            if(childAudioView!=null){
                childAudioView.pause();
            }
            Log.e("eee","暂停:"+getBindingAdapterPosition());
        }

        private void release(){
            if(childAudioView!=null){
                childAudioView.release();
            }
        }
    }

    public void pause(){
        for (int i = 0; i < itemAskList.size(); i++) {
            notifyItemChanged(i,"pause");
        }
    }

    public void release(){
        for (int i = 0; i < itemAskList.size(); i++) {
            notifyItemChanged(i,"release");
        }
    }

}
